<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane v-for="item in tabsList" :label="item.label" :name="item.name" />
    </el-tabs>
    <div class="coupon-add">
      <div class="coupon-search">
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="批次ID" prop="batchId">
            <el-input v-model="queryParams.batchId" placeholder="批次ID" />
          </el-form-item>
          <el-form-item label="优惠券名称" prop="couponName">
            <el-input v-model="queryParams.couponName" placeholder="优惠券名称" />
          </el-form-item>
          <el-form-item label="创建日期" prop="date">
            <el-date-picker v-model="queryParams.date" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getTableData">筛选</el-button>
            <el-button @click="resetSearchForm">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="coupon-button">
        <el-button type="primary" @click="showCouponForm">创建优惠券</el-button>
      </div>
    </div>
    <el-table :data="tableData" v-loading="tableLoading">
      <el-table-column label="序号" type="index" :index="indexMethod" />
      <el-table-column prop="batchId" label="批次ID" />
      <el-table-column prop="couponName" label="券名称" />
      <el-table-column prop="totalQuantity" label="库存" />
      <el-table-column prop="orderType" label="适用订单">
        <template slot-scope="scope">
          {{ orderType[scope.row.orderType] }}
        </template>
      </el-table-column>
      <el-table-column prop="distributionMethod" label="发放方式">
        <template slot-scope="scope">
          {{ sendType[scope.row.distributionMethod] }}
        </template>
      </el-table-column>
      <el-table-column prop="createBy" label="创建人" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-switch style="margin-right: 10px;" :value="scope.row.status" active-value="0" inactive-value="1"
            @change="($event) => openCoupon($event, scope.row)">
          </el-switch>
          <el-button type="text" size="small" @click="viewCoupon(scope.row)">查看</el-button>
          <el-button type="text" size="small" @click="copyItem(scope.row)">复制</el-button>
        </template>
      </el-table-column>
    </el-table>
    <InBody v-show="total > 0">
      <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getTableData" />
    </InBody>
    <couponForm ref="couponModal" :couponType="activeName" :getTableData="getTableData" />
  </div>
</template>

<script>
import { tabsList, orderType, sendType } from '@/constants/coupon';
import { queryCouponList, openCouponItem } from '@/api/coupon';
import moment from 'moment';
import couponForm from './couponForm.vue';

export default {
  components: {
    couponForm
  },
  data() {
    return {
      tabsList,
      orderType,
      sendType,
      activeName: 'ORDER_DISCOUNT',
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        batchId: '',
        couponName: '',
        date: []
      },
      tableData: [],
      tableLoading: false
    }
  },
  mounted() {
    this.getTableData();
  },
  methods: {
    indexMethod(index) {
      return index + 1;
    },
    handleClick() {
      this.getTableData();
    },
    resetSearchForm() {
      Object.assign(this.queryParams, this.$options.data().queryParams)
      this.getTableData();
    },
    async getTableData() {
      this.tableLoading = true
      const params = {
        ...this.queryParams,
        createStartTime: this.queryParams.date.length > 0 ? moment(this.queryParams.date[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        createEndTime: this.queryParams.date.length > 0 ? moment(this.queryParams.date[1]).format('YYYY-MM-DD 23:59:59') : undefined,
        couponType: this.activeName
      }
      delete params.date;
      const { code, rows, total } = await queryCouponList(params)
      this.tableLoading = false;
      if (code !== 200) return;
      this.total = +total;
      this.tableData = rows
    },
    showCouponForm() {
      this.$refs.couponModal.showModal('form')
    },
    openCoupon(event, item) {
      this.$confirm(`确定${parseInt(event) ? '禁用' : '启用'}吗？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { code } = await openCouponItem({ id: item.batchId, status: parseInt(event) })
        if (code !== 200) return;
        this.$message({ message: `${parseInt(event) ? '禁用' : '启用'}成功`, type: 'success' })
        return this.getTableData();
      })
        .catch()
    },
    viewCoupon(item) {
      this.$refs.couponModal.queryCouponDetail(item.batchId)
    },
    copyItem(item) {
      const newValue = { ...item };
      newValue.subOrderType = JSON.parse(newValue.subOrderType)
      newValue.ruleDetails = JSON.parse(newValue.ruleDetails)
      newValue.validityDetails = JSON.parse(newValue.validityDetails);
      newValue.alertSwitch = newValue.alertSwitch === '0';
      if (newValue.validityDetails.start_date) {
        newValue.validityDetails.date = [newValue.validityDetails.start_date, newValue.validityDetails.end_date]
      }
      delete newValue.batchId;
      delete newValue.status;
      this.$refs.couponModal.changeFormValue(newValue)
    }
  }
}
</script>
<style scoped lang="scss">
.coupon-add {
  width: 100%;
  height: auto;
  display: grid;
  align-items: flex-end;
  grid-template-columns: 85% 15%;
  margin-bottom: 15px;

  div {
    &.coupon-search {}

    &.coupon-button {
      text-align: right;
    }
  }
}
</style>
